package com.nc.shop.service.controller;

import cn.hutool.db.sql.Order;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.nc.shop.service.dao.OrderDao;
import com.nc.shop.service.model.dto.CarDto;
import com.nc.shop.service.model.entity.CarEntity;
import com.nc.shop.service.model.entity.OrderEntity;
import com.nc.shop.service.service.OrderService;
import com.nc.shop.service.service.RedisService;
import com.plug.BeanUtil;
import com.plug.result.ReqPage;
import com.plug.result.RetResponse;
import com.plug.result.RetResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;

/**
 * 创建人:    xvzhe
 * 创建时间:
 * 修改时间:
 * 版本:      v1.0
 */
@RestController
@RequestMapping("v1/order")
@Api
public class OrderController {
    @Autowired
    OrderService orderService;
    @Autowired
    OrderDao orderDao;
    @Autowired
    RedisService redisService;
    @Autowired
    HttpServletRequest request;

    @ApiOperation("根据购物车id生成订单")
    @PostMapping("add")
    public RetResult insert(@RequestBody List<String> carIds) {
        return orderService.addOrder(carIds);
    }

    @PostMapping("parent/all")
    @ApiOperation("获得所有订单")
    public RetResult parent(@RequestBody ReqPage reqPage) {
        JSONObject req = Optional.ofNullable(reqPage.getCommon()).orElseGet(JSONObject::new);
        OrderEntity entity = JSON.parseObject(req.toJSONString(), OrderEntity.class);
        entity.setType(0);
        int page = reqPage.getPage() - 1;
        int size = reqPage.getLimit();
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "modifiedTime");
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<OrderEntity> example = Example.of(entity, matcher);
        Page<OrderEntity> pages = orderDao.findAll(example, pageable);
        return RetResponse.makeRsp(0, "成功", pages.getContent(), (int) pages.getTotalElements());
    }

    @ApiOperation("根据id获得订单项")
    @GetMapping("item/{parentId}")
    public RetResult item(@PathVariable String parentId) {
        return RetResponse.makeOKRsp(orderDao.findByParentId(parentId));
    }

    @PostMapping("parent/user")
    @ApiOperation("获得当前登录人的订单")
    public RetResult parentUser() {
        net.sf.json.JSONObject user = net.sf.json.JSONObject.fromObject(redisService.get(request.getHeader("token")));
        return RetResponse.makeOKRsp(orderDao.findByUserId(user.getString("id")));
    }
}
